package net.omnivention.wulumuqi;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.log4j.Logger;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.xpath.XPath;

public class WuluUtil {
	private final static Logger logger = Logger.getLogger(WuluUtil.class);
	
	public static String getContextURL(String url) {
		int i = url.lastIndexOf("/");
		return url.substring(0, i + 1);
	}

	public static String getResource(String resourceURL) {
		StringBuffer buf = new StringBuffer(100);
		try {
			URL u = new URL(resourceURL);
			BufferedReader reader = null;
			try {
				reader = new BufferedReader(new InputStreamReader(u.openConnection().getInputStream()));
				String line = null;
				while ((line = reader.readLine()) != null) {
					buf.append(line).append("\n");
				}
			} catch (IOException e) {
				logger.error(e,e);
				throw new RuntimeException("Problem opening stream to " + resourceURL);
			} finally {
				if (reader != null) {
					try {
						reader.close();
					} catch (IOException e) {
					}
				}
			}

		} catch (MalformedURLException e) {
			logger.error(e,e);
			throw new RuntimeException("Malformed URL " + resourceURL);
		}

		return buf.toString();
	}

	public static HtmlDocument parseDocument(String docURL) throws JDOMException, IOException {
		SAXBuilder parser = new SAXBuilder(false);
		parser.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
		parser.setFactory(new WuluJDOMFactory());
		HtmlDocument document = (HtmlDocument) parser.build(docURL);
		return document;
	}

	public static Format getFormatter() {
		Format format = Format.getPrettyFormat(); //TODO: create own formatter
		format.setOmitDeclaration(true);
		format.setExpandEmptyElements(true);
		return format;
	}

	public static XPath createXPath(String xpathExpression) throws JDOMException {
		XPath xpath = XPath.newInstance(xpathExpression);
		xpath.addNamespace("html", "http://www.w3.org/1999/xhtml");
		return xpath;
	}

}
